package com.hzyl.famousreader.wxapi;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;

import cn.pedant.SweetAlert.SweetAlertDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.hzyl.famousreader.Constant;
import com.hzyl.famousreader.repository.webservice.RetrofitClient;
import com.hzyl.famousreader.repository.webservice.api.UserService;
import com.hzyl.famousreader.repository.webservice.model.Result;
import com.hzyl.famousreader.repository.webservice.model.WechatUser;
import com.hzyl.famousreader.view.activity.MainActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.hzyl.famousreader.App.WECHAT_API;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
  private static final int RETURN_MSG_TYPE_LOGIN = 1;
  private static final int RETURN_MSG_TYPE_SHARE = 2;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LogUtils.i("WXEntryActivity被调用了");
    //MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL);
    //如果没回调onResp，八成是这句没有写
    WECHAT_API.handleIntent(getIntent(), this);
  }

  // 微信发送请求到第三方应用时，会回调到该方法
  @Override
  public void onReq(BaseReq req) {
  }

  // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
  //app发送消息给微信，处理返回消息的回调
  @Override
  public void onResp(BaseResp resp) {
    LogUtils.i("data", resp.errCode + "");
    switch (resp.errCode) {
      case BaseResp.ErrCode.ERR_AUTH_DENIED:
      case BaseResp.ErrCode.ERR_USER_CANCEL:
        if (RETURN_MSG_TYPE_SHARE == resp.getType())
          new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.ERROR_TYPE)
            .setTitleText("分享失败")
            .show();
        else
          new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.ERROR_TYPE)
            .setTitleText("登录失败")
            .show();
        finish();
        break;
      case BaseResp.ErrCode.ERR_OK:
        switch (resp.getType()) {
          case RETURN_MSG_TYPE_LOGIN:
            //拿到了微信返回的code,立马再去请求access_token
            String code = ((SendAuth.Resp) resp).code;

            UserService userService = RetrofitClient.getInstance().create(UserService.class);
            Call<Result<WechatUser>> call = userService.wechatLogin(code);
            call.enqueue(new Callback<Result<WechatUser>>() {
              @Override
              public void onResponse(Call<Result<WechatUser>> call, Response<Result<WechatUser>> response) {
                Result<WechatUser> result = response.body();
                if(result.getErrno() == 0) {
                  SPUtils.getInstance().put(Constant.SP_IS_LOGIN, true);
                  SPUtils.getInstance().put(Constant.SP_USER_NAME, result.getData().getNickname());
                  new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.SUCCESS_TYPE)
                    .setTitleText("微信登陆成功")
                    .show();
                  new CountDownTimer(2000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {

                    }

                    @Override
                    public void onFinish() {
                      ActivityUtils.startActivity(MainActivity.class);
                    }
                  }.start();
                } else {new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.ERROR_TYPE)
                  .setTitleText("微信登陆失败")
                  .show();
                  finish();

                }
              }

              @Override
              public void onFailure(Call<Result<WechatUser>> call, Throwable t) {
                finish();
                new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
                  .setTitleText("请求微信登陆异常")
                  .show();
              }
            });
            break;

          case RETURN_MSG_TYPE_SHARE:
            new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.SUCCESS_TYPE)
              .setTitleText("微信分享成功")
              .show();
            finish();
            break;
        }
        break;
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
  }

  @Override
  protected void onPause() {
    super.onPause();
  }
}
